package channel

import (
	"fmt"
	"time"
)

//channel 是goroutin之间的通信机制
//用channel必须有goroutine

/*func ChannelDemo(){
	//var c chan int//nil
	c := make(chan int)
	c <-1
	c <-2
	n :=<-c
	fmt.Println(n)
}*/

/*
func ChannelDemo() {
	//var c chan int//nil
	c := make(chan int)
	go func() {
		n := <-c
		fmt.Println(n)
		n = <-c
		fmt.Println(n)
	}()
	c <- 1
	c <- 2
	time.Sleep(time.Second)
}
*/

//channel 可作为参数,数组类型,也可以作为返回值
/*
func worker(id int,c chan int){
	for {
		fmt.Printf("worker %d receive %c\n",id,<-c)
	}
}

func ChannelDemo(){
	var channels [10]chan int
	for i:=0;i<10;i++{
		channels[i] = make(chan int)
		go worker(i,channels[i])
	}

	for i:=0;i<10;i++{
		channels[i]<- 'a'+i
	}

	time.Sleep(time.Second)
}
*/

//常用写法
//创建以后开一个goroutine,中间编写要干的的事情,然后返回
//channel还分只读(<-chan)和只写(chan<-)
/*
func createWorker(id int) chan<- int{
	worker := make(chan int)
	go func() {
		for {
			fmt.Printf("worker %d receive %c\n",id,<-worker)
		}
	}()
	return worker
}

func ChannelDemo(){
	var channels [10]chan<- int
	for i:=0;i<10;i++{
		channels[i] = createWorker(i)
	}

	for i:=0;i<10;i++{
		channels[i]<- 'a'+i
	}

	time.Sleep(time.Second)
}
*/

// closeChannel

// 发送方可以close

func work(worker chan int) {
	//for {
	//	n, ok := <-worker
	//	if !ok {
	//		break
	//	}
	//	fmt.Printf("worker receive %d\n", n)
	//}

	for n := range worker {
		fmt.Printf("worker receive %d\n", n)
	}
}

func createBufferWorker(buffersize int) chan int {
	worker := make(chan int, buffersize)
	go work(worker)
	return worker
}

func ChannelDemo() {
	worker := createBufferWorker(10)

	go func() {
		for i := 0; i < 100; i++ {
			worker <- i
		}
		//close(worker)
	}()

	time.Sleep(10 * time.Second)
}
